package com.example.bighomework.fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.bighomework.MainActivity;
import com.example.bighomework.R;
import com.example.bighomework.adapter.DailyWeatherAdapter;
import com.example.bighomework.adapter.HourlyWeatherAdapter;
import com.example.bighomework.bean.WeatherResponse;
import com.google.gson.Gson;

import org.json.JSONObject;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RecommendFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RecommendFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private TextView cityTextView, currentTempTextView, minMaxTempTextView;
    private TextView dressingIndexTextView, carWashingIndexTextView;
    private RecyclerView hourlyRecyclerView, dailyRecyclerView;
    private View inflate;

    public RecommendFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RecommendFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RecommendFragment newInstance(String param1, String param2) {
        RecommendFragment fragment = new RecommendFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        inflate = inflater.inflate(R.layout.fragment_recommend, container, false);

        cityTextView = inflate.findViewById(R.id.city_text_view);
        currentTempTextView =inflate. findViewById(R.id.current_temp_text_view);
        minMaxTempTextView = inflate.findViewById(R.id.min_max_temp_text_view);
        dressingIndexTextView = inflate.findViewById(R.id.dressing_index_text_view);
        carWashingIndexTextView = inflate.findViewById(R.id.car_washing_index_text_view);
        hourlyRecyclerView = inflate.findViewById(R.id.hourly_recycler_view);
        dailyRecyclerView = inflate.findViewById(R.id.daily_recycler_view);

        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        String url = "https://api.open-meteo.com/v1/forecast?latitude=39.9&longitude=116.4&current_weather=true&hourly=temperature_2m,weathercode&daily=weathercode,temperature_2m_max,temperature_2m_min&timezone=auto&forecast_days=8";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Gson gson = new Gson();
                        WeatherResponse weatherResponse = gson.fromJson(response.toString(), WeatherResponse.class);

                        cityTextView.setText("北京");
                        // 设置当前温度
                        currentTempTextView.setText(  weatherResponse.current_weather.temperature + "°C");
                        // 设置最低最高气温
                        double minTemp = Double.MAX_VALUE, maxTemp = Double.MIN_VALUE;
                        for (double temp : weatherResponse.hourly.temperature_2m) {
                            minTemp = Math.min(minTemp, temp);
                            maxTemp = Math.max(maxTemp, temp);
                        }
                        minMaxTempTextView.setText("最低气温: " + minTemp + "°C / 最高气温: " + maxTemp + "°C");
                        // 设置穿衣指数和洗车指数（当前接口未提供，先占位）
                        dressingIndexTextView.setText("穿衣指数: 今日温度较高，注意紫外线");
                        carWashingIndexTextView.setText("洗车指数: 暂无数据");

                        // 设置未来24小时天气
                        HourlyWeatherAdapter hourlyAdapter = new HourlyWeatherAdapter(
                                weatherResponse.hourly.time, weatherResponse.hourly.temperature_2m);
                        hourlyRecyclerView.setAdapter(hourlyAdapter);
                        hourlyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));

                        // 设置未来7天天气
                        DailyWeatherAdapter dailyAdapter = new DailyWeatherAdapter(
                                weatherResponse.daily.time, weatherResponse.daily.temperature_2m_max, weatherResponse.daily.temperature_2m_min);
                        dailyRecyclerView.setAdapter(dailyAdapter);
                        dailyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getActivity(), "请求失败: " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
            @Override
            public java.util.Map<String, String> getHeaders() throws AuthFailureError {
                java.util.HashMap<String, String> headers = new java.util.HashMap<>();
                headers.put("Content-Type", "application/json");
                return headers;
            }
        };

        requestQueue.add(jsonObjectRequest);
        return inflate;
    }
}